import 'package:flutter/material.dart';
import 'package:flutter_redis/controller/theme_controller.dart';
import 'package:get/get.dart';
import '../controller/redis_controller.dart';
import '../models/redis_config.dart';

class RedisConfigPage extends StatefulWidget {
  final RedisConfig? config;

  const RedisConfigPage({super.key, this.config});

  @override
  State<RedisConfigPage> createState() => _RedisConfigPageState();
}

class _RedisConfigPageState extends State<RedisConfigPage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _hostController;
  late TextEditingController _portController;
  late TextEditingController _usernameController;
  late TextEditingController _passwordController;
  bool _isEditing = false;

  final _controller = Get.find<RedisController>();
  final ThemeController themeController = Get.put(ThemeController());

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.config?.name ?? '');
    _hostController = TextEditingController(text: widget.config?.host ?? '');
    _portController = TextEditingController(
      text: widget.config?.port.toString() ?? '6379',
    );
    _usernameController = TextEditingController(
      text: widget.config?.username ?? '',
    );
    _passwordController = TextEditingController(
      text: widget.config?.password ?? '',
    );
    _isEditing = widget.config == null;
  }

  @override
  void dispose() {
    _nameController.dispose();
    _hostController.dispose();
    _portController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  Future<void> _save() async {
    if (!_formKey.currentState!.validate()) return;

    final config = RedisConfig(
      id: widget.config?.id,
      name: _nameController.text,
      host: _hostController.text,
      port: int.parse(_portController.text),
      username: _usernameController.text.isEmpty
          ? null
          : _usernameController.text,
      password: _passwordController.text.isEmpty
          ? null
          : _passwordController.text,
    );

    await _controller.saveConfig(config);
    Get.back();
  }

  void _toggleEdit() async {
    if (widget.config?.isConnected ?? false) {
      final result = await Get.dialog<bool>(
        AlertDialog(
          title: const Text('断开连接'),
          content: const Text('编辑配置需要断开当前连接，是否继续？'),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text('确认'),
            ),
          ],
        ),
      );

      if (result != true) return;
      await _controller.disconnect();
    }

    setState(() {
      _isEditing = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.config == null ? '新建Redis连接' : widget.config!.name),
        actions: [
          if (widget.config != null && !_isEditing)
            IconButton(icon: const Icon(Icons.edit), onPressed: _toggleEdit),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 18),
        child: Card(
          elevation: 2,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 18),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    controller: _nameController,
                    decoration: const InputDecoration(
                      labelText: '名称 *',
                      hintText: '输入连接名称',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                      ),
                      isDense: true,
                    ),
                    enabled: _isEditing,
                    validator: (v) => v?.isEmpty == true ? '请输入名称' : null,
                  ),
                  const SizedBox(height: 18),
                  TextFormField(
                    controller: _hostController,
                    decoration: const InputDecoration(
                      labelText: '主机地址 *',
                      hintText: '输入Redis主机地址',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                      ),
                      isDense: true,
                    ),
                    enabled: _isEditing,
                    validator: (v) => v?.isEmpty == true ? '请输入主机地址' : null,
                  ),
                  const SizedBox(height: 18),
                  TextFormField(
                    controller: _portController,
                    decoration: const InputDecoration(
                      labelText: '端口 *',
                      hintText: '输入Redis端口',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                      ),
                      isDense: true,
                    ),
                    enabled: _isEditing,
                    keyboardType: TextInputType.number,
                    validator: (v) {
                      if (v?.isEmpty == true) return '请输入端口';
                      final port = int.tryParse(v!);
                      if (port == null || port <= 0 || port > 65535) {
                        return '请输入有效的端口号(1-65535)';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 18),
                  TextFormField(
                    controller: _usernameController,
                    decoration: const InputDecoration(
                      labelText: '用户名',
                      hintText: '输入Redis用户名（可选）',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                      ),
                      isDense: true,
                    ),
                    enabled: _isEditing,
                  ),
                  const SizedBox(height: 18),
                  TextFormField(
                    controller: _passwordController,
                    decoration: const InputDecoration(
                      labelText: '密码',
                      hintText: '输入Redis密码（可选）',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                      ),
                      isDense: true,
                    ),
                    enabled: _isEditing,
                    obscureText: true,
                  ),
                  const SizedBox(height: 28),
                  if (_isEditing)
                    SizedBox(
                      width: double.infinity,
                      height: 44,
                      child: ElevatedButton(
                        onPressed: _save,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: themeController.primaryColor.value,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(6),
                          ),
                          elevation: 0,
                        ),
                        child: const Text('保存', style: TextStyle(fontSize: 16)),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
